package com.dongao.marketing.common.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class CreateImageUtils {

	/**
	 * 生成图片
	 * 
	 * @param width
	 * @param height
	 * @param str
	 * @param path
	 * @param fontSize
	 * @throws IOException
	 */
	public static void createImg(int width, int height, String str,
			String path, int fontSize) throws IOException {
		File file = new File(path);
		if (!file.exists() && !file.isDirectory()) {
			file.mkdirs();
		}

		Font font = new Font(Font.SANS_SERIF, Font.PLAIN, fontSize);
		BufferedImage bi = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = (Graphics2D) bi.getGraphics();
		g2.setBackground(Color.WHITE);
		g2.clearRect(0, 0, width, height);
		g2.setPaint(Color.BLACK);
		g2.setFont(font);

		FontRenderContext context = g2.getFontRenderContext();
		Rectangle2D bounds = font.getStringBounds(str, context);
		System.out.println(bounds.getWidth());
		System.out.println(bounds.getHeight());
		double x = (width - bounds.getWidth()) / 2;
		double y = (height - bounds.getHeight()) / 2;
		double ascent = -bounds.getY();
		double baseY = y + ascent;

		g2.drawString(str, (int) x, (int) baseY);

		ImageIO.write(bi, "jpg", file);

	}

	public static void main(String[] args) throws Exception {
		int width = 80;
		int height = 25;
		String s = "12312";
		String path = "d:/aaa/image.jpg";
		createImg(width, height, s, path, 25);
	}
}